package com.sysware;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.ueditor.ActionEnter;

@WebServlet("/UediterFileUpload")
public class UediterFileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setHeader("Content-Type", "text/html");
		String path = UediterFileUpload.class.getResource("").toString();
		String absPath = path.substring(path.indexOf(":") + 2, path.indexOf("classes")) + "classes/";
		// config.json
		String data = new ActionEnter(request, absPath).exec();
		System.out.println(data);
		try {
			JSONObject obj = new JSONObject(data);
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath() + "/";
			String action = request.getParameter("action");
			if ("listimage".equals(action) || "listfile".equals(action)) {
				JSONArray jsonarray = obj.getJSONArray("list");
				if (jsonarray != null) {
					for (int i = 0; i < jsonarray.length(); i++) {
						JSONObject o = jsonarray.getJSONObject(i);
						if (o != null) {
							String url = o.getString("url");
							if (url != null) {
								o.put("url", basePath + url.substring(url.indexOf("/upload") + 1, url.length()));
							}
						}
					}
				}
			} else {
				String url = obj.getString("url");
				obj.put("url", "../" + url.substring(6, url.length()));
			}
			response.getWriter().write(obj.toString());
		} catch (JSONException e) {
			response.getWriter().write(data);
		}
	}

}
